<?php

namespace App\Models\Api;

use Carbon\Carbon;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Site;
use JMessage\IM\User as IMUser;
use JMessage\JMessage;

class User extends Authenticatable
{
    protected $table = 'personal_users';//表

    protected $primaryKey = 'uid';//主键

    const CREATED_AT = 'regtime';
    const UPDATED_AT = 'updatetime';

    protected $guarded = [];

    protected $hidden = ['password', 'remember_token', 'regtime',
        'updatetime', 'last_login_time', 'last_login_ip', 'resume',
        'device_token', 'pwd_hash', 'email_id', 'mobile_id',
        'qqopenid', 'wechatopenid', 'wechatmpopenid', 'wechatunionid',
        'part_time_resume'];

    protected $casts = [
        'uid' => 'string',
    ];

    public function part_time_resume()
    {
        return $this->hasOne(PartTimeResume::class, 'uid', 'uid')
            ->select(['id', 'uid']);
    }

    public function getPartResumeIdAttribute()
    {
        return $this->part_time_resume ? $this->part_time_resume->id : '';
    }

    public function resume()
    {
        return $this->hasOne(Resume::class, 'uid', 'uid')
            ->orderBy('updatetime', 'desc')
            ->where('default', 1)//默认简历
            ->select('id', 'uid', 'bkresume_status', 'avatar', 'name', 'sex',
                'intentionjobs', 'introduction', 'chkphoto_open', 'mobile', 'job_status');
    }

    public function getResumeIdAttribute()
    {
        return $this->resume ? $this->resume->id : '';
    }

    public function getResumeEidAttribute()
    {
        return $this->resume ? idEncryption($this->resume->id) : '';
    }

    public function getResumeStatusAttribute()
    {
        return $this->resume ? $this->resume->bkresume_status : '';
    }

    public function getAvatarAttribute()
    {
        return $this->resume ? $this->resume->avatar : '';
    }

    public function getNameAttribute()
    {
        return $this->resume ? $this->resume->name : '';
    }

    public function getSexAttribute()
    {
        return $this->resume ? $this->resume->sex : '0';
    }

    public function getChkphotoOpenAttribute()
    {
        return $this->resume ? $this->resume->chkphoto_open : '0';
    }

    public function getResumeMobileAttribute()
    {
        return $this->resume ? $this->resume->mobile : '';
    }

    public function getJobStatusAttribute()
    {
        return $this->resume ? $this->resume->job_status : '1';
    }

    /** 简历完善度
     * @return float
     */
    public function getDegreeAttribute()
    {
        if (is_null($this->resume)) {
            return 0.0;
        }
        $completionArr[0] = 1;

        $completionArr[1] = !empty($this->resume->intentionjobs) ? 1 : 0;
        $completionArr[2] = !empty($this->resume->introduction) ? 1 : 0;

        $tables = ['resume_work_exp', 'resume_education_exp', 'resume_project_exp',
            'resume_language_skill', 'resume_skill', 'resume_certificate',
            'resume_other', 'resume_works'];

        foreach ($tables as $table) {
            $completionArr[] = \DB::table($table)
                ->where(['uid' => $this->uid, 'resume_id' => $this->resume->id])
                ->count() > 0 ? 1 : 0;
        }

        $percentage = 0;
        for ($i = 0; $i < 11; $i++) {
            if ($completionArr[$i] == 1) {
                $percentage += ($i == 8 || $i == 9) ? 5 : 10;
            }
        }

        return strval($percentage / 100);
    }

    /** 获取聊天密码
     * @return mixed
     */
    public function getChatPwdAttribute()
    {
        $where = [
            'uid' => $this->uid,
            'type' => 'chat_pwd',
        ];
        $p = \DB::table('personal_bind')->where($where)->first();

        if (!empty($p)) {
            return $p->keyid;
        }

        //注册聊天账号
        $appKey = Site::get('personal_app_key');
        $masterSecret = Site::get('personal_master_secret');

        $username = 'personal_' . $this->uid;
        $jm = new JMessage($appKey, $masterSecret);
        $user = new IMUser($jm);
        $pwd = str_random(20);
        $response = $user->register($username, $pwd);

        //注册失败
        if ($response['http_code'] < 200 || $response['http_code'] > 299) {
            if (array_key_exists('error', $response['body'][0])) {
                if ($response['body'][0]['error']['code'] == 899001) {//已经注册过了
                    $pwd = $username;
                } else {
                    return '';
                }
            } else {
                return '';
            }
        }

        //保存密码
        $create = [
            'uid' => $this->uid,
            'type' => 'chat_pwd',
            'keyid' => $pwd,
            'created_at' => Carbon::now()
        ];
        \DB::table('personal_bind')->insert($create);

        //给聊天账户赋值信息
        if (!empty($this->resume)) {
            $user->update($username, [
                'nickname' => $this->resume->name,
                'address' => $this->resume->avatar,
                'gender' => $this->resume->sex,
                'region' => idEncryption($this->resume->id)
            ]);
        }
        return $pwd;
    }
}